<template>
  <div class="page-container clients">
    <van-nav-bar
      title="服务对象管理"
      left-text="返回"
      left-arrow
      fixed
      placeholder
      @click-left="onClickLeft"
    />

    <!-- 服务对象列表 -->
    <div class="client-list" :style="{padding:userStore.userInfo.ageGroup === 1 ? '10px' : ''}">
      <van-cell-group inset v-if="clientList.length" :style="{margin:userStore.userInfo.ageGroup === 1 ? '0' : ''}">
        <van-swipe-cell v-for="(client, index) in clientList" :key="index" :style="{marginTop:userStore.userInfo.ageGroup === 1 ? '15px' : ''}" >
          <van-cell :border="false" center>
            <template #icon>
              <van-icon name="manager-o" size="24" class="client-icon" />
            </template>
            <template #title>
              <div class="client-info">
                <span class="client-name" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '30px' : ''}">{{ client.objectName }}</span>
                <van-tag color="pink" text-color="white" size="small" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '20px' : '',padding:userStore.userInfo.ageGroup === 1 ? '3px' : ''}">{{ client.age }}岁</van-tag>
                <van-tag type="primary" size="small" v-if="client.defaultPatient" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '20px' : '',padding:userStore.userInfo.ageGroup === 1 ? '3px' : ''}">默认</van-tag>
              </div>
            </template>
            <template #label>
              <div>
                <span :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '20px' : ''}">电话：{{ client.phone }}</span>
              </div>
              <div class="client-detail">
                <span :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '20px' : ''}">地址：{{ client.address }}</span>
              </div>
            </template>
            <template #right-icon>
              <van-button
                size="small"
                type="primary"
                plain
                @click="editClient(client)"
                :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '20px' : ''}"
              >
                编辑
              </van-button>
            </template>
          </van-cell>
          <template #right>
            <van-button
              square
              type="danger"
              text="删除"
              class="delete-button"
              @click="deleteClient(client)"
            />
          </template>
        </van-swipe-cell>
      </van-cell-group>

      <div class="empty-tip" v-else>
        <van-empty description="暂无服务对象" />
      </div>
    </div>

    <!-- 添加服务对象按钮 -->
    <div class="add-button">
      <van-button type="primary" block icon="plus" @click="showAddDialogObject()">
        添加服务对象
      </van-button>
    </div>

    <!-- 添加/编辑服务对象弹窗 -->
    <van-dialog
      v-model:show="showAddDialog"
      :title="isEdit ? '编辑服务对象' : '添加服务对象'"
      show-cancel-button
      @confirm="onSubmit"
      :before-close="onBeforeClose"
      :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '25px' : ''}"
    >
      <van-form>
        <van-cell-group inset>
          <van-field
            v-model="formData.objectName"
            label="姓名"
            placeholder="请输入姓名"
            :rules="[{ required: true, message: '请输入姓名' },
            {
              pattern: /^[\u4e00-\u9fa5A-Za-z]{2,10}$/, // 正则表达式校验姓名格式
              message: '姓名必须为2-10个中文字符或英文字母，且不能包含数字',
            },
          ]"
            :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '20px' : ''}"
          />
          <van-field
            v-model="formData.age"
            label="年龄"
            placeholder="请输入年龄"
            :rules="[{ required: true, message: '请输入年龄' },
            {
              pattern: /^(0|[1-9]\d{0,2})$/, // 正则表达式校验年龄格式
              message: '年龄必须为0-120之间的整数',
            },
            {
              validator: (value) => value >= 0 && value <= 120, // 自定义校验函数
              message: '年龄必须在0到120岁之间',
            },]"
            :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '20px' : ''}"
          />
          <van-field
            v-model="formData.phone"
            type="tel"
            label="手机号"
            placeholder="请输入手机号"
            :rules="[{ required: true, message: '请输入手机号' },
            {
            pattern: /^1[3-9]\d{9}$/, // 正则表达式校验手机号格式
            message: '请输入正确的手机号',
            }]"
            :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '20px' : ''}"
          />
          <van-field
            v-model="formData.address"
            label="地址"
            placeholder="请输入地址"
            :rules="[{ required: true, message: '请输入地址' },
            {
              pattern: /^[\u4e00-\u9fa5A-Za-z0-9\s\-/]{5,100}$/, // 正则表达式校验地址格式
              message: '地址必须为5-100个字符，且只能包含中文、英文、数字、空格和常见符号',
            },]"
            :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '20px' : ''}"
          />
          <van-cell center title="设为默认服务对象" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '20px' : ''}">
            <template #right-icon>
              <van-switch v-model="formData.defaultPatient" size="24" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-form>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showConfirmDialog, showToast } from 'vant'
import { serviceObjectApi } from '@/api'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()

const router = useRouter()

const showAddDialogObject = () => {
  formData.value = {}
  showAddDialog.value = true
}

// 服务对象列表
const clientList = ref([
  {
    id: 1,
    objectName: '张三',
    address: '110101199001011234',
    phone: '13800138000',
    age:null,
    defaultPatient: 1
  },
  {
    id: 2,
    objectName: '李四',
    address: '110101199001011235',
    phone: '13800138001',
    age:null,
    defaultPatient: 0
  }
])

// 表单数据
const formData = ref({
  objectName: '',
  address: '',
  phone: '',
  age:null,
  defaultPatient: 0
})

// 控制添加/编辑弹窗显示
const showAddDialog = ref(false)
const isEdit = ref(false)
const editingId = ref(null)

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 编辑服务对象
const editClient = (client) => {
  isEdit.value = true
  editingId.value = client.id
  formData.value = { ...client }
  formData.value.defaultPatient = formData.value.defaultPatient === 0? false : true
  showAddDialog.value = true
}

// 删除服务对象
const deleteClient = async (client) => {
  try {
    await showConfirmDialog({
      title: '提示',
      message: '确定要删除该服务对象吗？'
    })
    const res = await serviceObjectApi.deleteServiceObject(client.id)
    if(res.code === 200){
      showToast('删除成功')
      getServiceObjectList(JSON.parse(localStorage.getItem('userInfo')).id)
    }else{
      showToast('删除失败')
    }
  } catch {
    // 用户取消操作
    showToast('已取消删除')
  }
}

// 提交表单
const onSubmit = async () => {
  // 表单校验规则
  const rules = {
    objectName: [
      { required: true, message: '请输入姓名' },
      { 
        pattern: /^[\u4e00-\u9fa5A-Za-z]{2,10}$/, 
        message: '姓名必须为2-10个中文字符或英文字母，且不能包含数字'
      }
    ],
    age: [
      { required: true, message: '请输入年龄' },
      {
        pattern: /^(0|[1-9]\d{0,2})$/,
        message: '年龄必须为0-120之间的整数'
      },
      {
        validator: (value) => value >= 0 && value <= 120,
        message: '年龄必须在0到120岁之间'
      }
    ],
    phone: [
      { required: true, message: '请输入手机号' },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: '请输入正确的手机号'
      }
    ],
    address: [
      { required: true, message: '请输入地址' },
      {
        pattern: /^[\u4e00-\u9fa5A-Za-z0-9\s\-/]{5,100}$/,
        message: '地址必须为5-100个字符，且只能包含中文、英文、数字、空格和常见符号'
      }
    ]
  }

  // 验证表单
  const validateField = (value, fieldRules) => {
    for (const rule of fieldRules) {
      if (rule.required && !value) {
        showToast(rule.message)
        return false
      }
      if (rule.pattern && !rule.pattern.test(value)) {
        showToast(rule.message)
        return false
      }
      if (rule.validator && !rule.validator(value)) {
        showToast(rule.message)
        return false
      }
    }
    return true
  }

  // 验证所有字段
  for (const [field, fieldRules] of Object.entries(rules)) {
    if (!validateField(formData.value[field], fieldRules)) {
      return false
    }
  }

  try {
    const params = {
      userId: JSON.parse(localStorage.getItem('userInfo')).id,
      ...formData.value,
      defaultPatient: formData.value.defaultPatient ? 1 : 0
    }

    if (isEdit.value) {
      // 编辑模式
      const res = await serviceObjectApi.uptadeServiceObject(params)
      if (res.code === 200) {
        showToast('编辑成功')
        await getServiceObjectList(params.userId)
        resetForm()
      } else {
        showToast('编辑失败')
      }
    } else {
      // 新增模式
      const res = await serviceObjectApi.addServiceObject(params)
      if (res.code === 200) {
        showToast('添加成功')
        await getServiceObjectList(params.userId)
        resetForm()
      } else {
        showToast('添加失败')
      }
    }
    return true
  } catch (error) {
    console.error('操作失败:', error)
    showToast('操作失败')
    return false
  }
}

const getServiceObjectList = async (userId) => {
  try{
    let params = {
    userId:userId,
  }
  const res = await serviceObjectApi.getServiceObjectList(params)
  if(res.code === 200){
  clientList.value = res.data.list
  }else{
    showToast('获取服务对象列表失败')
  }
  }catch(error){
    console.log(error)
    showToast('获取服务对象列表失败')
  }
}

// 弹窗关闭前的回调
const onBeforeClose = (action) => {
  if (action === 'cancel') {
    resetForm()
    return true
  }
  return true
}

// 重置表单
const resetForm = () => {
  formData.value = {
    objectName: '',
    address: '',
    phone: '',
    age:null,
    defaultPatient: 0
  }
  isEdit.value = false
  editingId.value = null
  showAddDialog.value = false
}

onMounted( async() => {
  let userId =JSON.parse(localStorage.getItem('userInfo')).id
  await getServiceObjectList(userId)
})
</script>

<style lang="scss" scoped>
.clients {
  padding-bottom: 80px;

  .client-list {
    padding: 16px;

    .client-icon {
      margin-right: 8px;
      color: var(--primary-color);
    }

    .client-info {
      display: flex;
      align-items: center;
      gap: 8px;

      .client-name {
        font-size: 16px;
        font-weight: 500;
      }
    }

    .client-detail {
      display: flex;
      gap: 16px;
      color: var(--text-color-secondary);
    }

    .delete-button {
      height: 100%;
    }
  }

  .empty-tip {
    padding: 40px 0;
  }

  .add-button {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 8px 16px;
    background: #fff;
    border-top: 1px solid var(--border-color);
  }
}
</style> 